package com.lineage.server.world;

import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.Instance.L1TrapInstance;
import com.lineage.server.model.L1Location;
import com.lineage.server.types.Point;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class WorldTrap {
  private static final Log _log = LogFactory.getLog(WorldTrap.class);
  
  private static WorldTrap _instance;
  
  private final HashMap<Integer, L1TrapInstance> _isTrap;
  
  public static WorldTrap get() {
    if (_instance == null)
      _instance = new WorldTrap(); 
    return _instance;
  }
  
  private WorldTrap() {
    this._isTrap = new HashMap<>();
  }
  
  public HashMap<Integer, L1TrapInstance> map() {
    return this._isTrap;
  }
  
  public void put(Integer key, L1TrapInstance value) {
    try {
      this._isTrap.put(key, value);
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  public void remove(Integer key) {
    try {
      this._isTrap.remove(key);
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  public void resetAllTraps() {
    Object[] array;
    int length = (array = this._isTrap.values().toArray()).length;
    int i = 0;
    while (i < length) {
      Object iter = array[i];
      L1TrapInstance trap = (L1TrapInstance)iter;
      trap.resetLocation();
      trap.enableTrap();
      i++;
    } 
  }
  
  public void onPlayerMoved(L1PcInstance pc) {
    L1Location loc = pc.getLocation();
    Object[] array;
    int length = (array = this._isTrap.values().toArray()).length;
    int i = 0;
    while (i < length) {
      Object iter = array[i];
      L1TrapInstance trap = (L1TrapInstance)iter;
      if (trap.isEnable() && loc.equals(trap.getLocation())) {
        trap.onTrod(pc);
        trap.disableTrap();
      } 
      i++;
    } 
  }
  
  public void onDetection(L1PcInstance pc) {
    L1Location loc = pc.getLocation();
    Object[] array;
    int length = (array = this._isTrap.values().toArray()).length;
    int i = 0;
    while (i < length) {
      Object iter = array[i];
      L1TrapInstance trap = (L1TrapInstance)iter;
      if (trap.isEnable() && loc.isInScreen((Point)trap.getLocation())) {
        trap.onDetection(pc);
        trap.disableTrap();
      } 
      i++;
    } 
  }
}
